<?php
namespace control;
/*
*联系人
*/

class kehuStaffClass extends adIndexClass
{
    private const title = '联系人';
    private const page = 'kehuStaff';
    private const table = 'kehu_staff';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'companyName'          => [
                        'name'  => "{l.kehuStaff.homeSearch.companyName}",
                        'width' => 150,
                    ],
                    'name' => [
                        'name'  => "{l.kehuStaff.homeSearch.name}",
                        'width' => 100,
                    ],
                    'sex'  => [
                        'name'  => "{l.kehuStaff.homeSearch.sex}",
                        'width' => 70,
                    ],
                    'department'         => [
                        'name'  => "{l.kehuStaff.homeSearch.department}",
                        'width' => 100,
                    ],
                    'position'          => [
                        'name'  => "{l.kehuStaff.homeSearch.position}",
                        'width' => 100,
                    ],
                    'tel'          => [
                        'name'  => "{l.kehuStaff.homeSearch.tel}",
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'phone'          => [
                        'name'  => "{l.kehuStaff.homeSearch.phone}",
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'WeChat'          => [
                        'name'  => "{l.kehuStaff.homeSearch.WeChat}",
                        'width' => 100,
                    ],
                    'qq'          => [
                        'name'  => '{l.kehuStaff.homeSearch.qq}',
                        'width' => 100,
                    ],
                    'birthDay'          => [
                        'name'  => '{l.kehuStaff.homeSearch.birthDay}',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'address'          => [
                        'name'  => '{l.kehuStaff.homeSearch.address}',
                        'width' => 150,
                    ],
                    'text'          => [
                        'name'  => '{l.kehuStaff.homeSearch.text}',
                        'width' => 150,
                    ],
                    'updateTime'          => [
                        'name'  => '{l.kehuStaff.homeSearch.updateTime}',
                        'width' => 150,
                        'sort' => 1,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    L('kehuStaff.home.companyName') => text(array("name" => "companyName")),
                    L('kehuStaff.home.contactName')   => text(array("name" => "contactName")),
                    L('kehuStaff.home.contactTel') => text(array("name" => "contactTel")),
                ],
                [
                    L('kehuStaff.home.text')  => text(array("name" => "text"))
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*客户列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        $button = "";
        if ($this->power('client', "staffEdit")) {
            $button .= "<span onclick=\"layer('" . self::page . "','edit',{id:'" . self::getId() . "'})\" class='spanButton'>".L('kehuStaff.homeSearch.new')."</span>\n";
        }
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"\" class='spanButton'>".L('kehuStaff.homeSearch.sendMsg')."</span>\n";
        }
        //导入
        if ($this->power(self::page, 'import')) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','importFrame',{cla:'".self::page."'})\">导入</span>";
        }
        if ($this->power(self::page, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."'})\">导出</span>";
        }
        if ($this->power('client', "staffDel")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">".L('kehuStaff.homeSearch.del')."</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "b.companyName" => $this->post('companyName'),//客户名称
            "a.name" => $this->post('contactName'),//客户名称
            "a.tel" => $this->post('contactTel'),//联系手机
            "a.text" => $this->post('text'),//备注
        );
        //全等查询数组
        $equal = [
            'a.coid'=>self::$coid
        ];
        $and = '';
        if (!$this->power(self::page,'seeAll')){
            $and.=" and a.stid = '".self::$stid."'";
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'updateTime',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(
                'updateTime'=>'a.updateTime'
            ),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)).$and;
        $page = $this->page(array(
            'field' => "a.*,b.companyName",
            "table" => "kehu_staff as a join kehu as b on a.khid = b.khid",
            "where" => $where,
            "order" => $orderBy['orderBy']
        ));
        $_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "edit" => array("title" => L('kehuStaff.homeSearch.edit'), "click" => "layer('" . self::page . "','edit',{id:'" . $array['id'] . "'})"),
                'follow' => array("title" => L('kehuStaff.homeSearch.addFollow'), "click" => "layer('" . self::page . "','add',{id:'" . $array['id'] . "'})"),
            );
            $liButton[] = $this->dominate($dominate);
            //已住人数
//            $livePeople = static::total(array('table'=>'dormitory_record','where'=>" and dormitoryId = '$array[id]' and state = '入住'"));
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "birthDay":
                        $row[] = self::null($array['birthDay']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件"client", "staffEdit"
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }



    /**
     * 添加更进
     * @return bool|string
     */
    public function add()
    {
        $kehuStaff = query("kehu_staff", " id = '" . $this->post('id') . "' ");
        $workFlowArray = explode("，", para("clientWorkFlow"));
        $plan = text(array("name" => "startDay", "laydate" => [], "title" => "", "class" => "text textPrice"));
        $quickArray = explode("，", para("followQuick"));
        $followQuick = "";
        foreach ($quickArray as $value) {
            $followQuick .= "<li onclick='followQuick(this)'>" . $value . "</li>";
        }

        $workFlowQuick = "";
        foreach ($workFlowArray as $value) {
            $workFlowQuick .= "<li onclick='workFlowQuick(this)'>" . $value . "</li>";
        }

        $html = "
			<div class='' orderPageDiv='record' style='margin: 10px'>
				<form name='followForm'>
				<textarea name='text' class='followTextarea height200' placeholder='".L('kehuStaff.add.newFollow')."'></textarea>
				<input name='targetId' type='hidden' value='" . $kehuStaff['id'] . "'>
				<ul class='followUl'>
				<li><p>".L('kehuStaff.add.nextFollowDate')."：" . $plan . "</p></li>
				<li><span>".L('kehuStaff.add.followType')."：</span><ul id='followQuick' style='display: inline-flex' class='followQuick'>" . $followQuick . "</ul>
				<li><span>".L('kehuStaff.add.workFlow')."：</span><ul  style='display: inline-flex' class='followQuick'>" . $workFlowQuick . "</ul></li>
				</ul>
				" . hidden(array('name' => 'followType', 'value' => '')) . hidden(array('name' => 'workFlow', 'value' => '')) . "
				</form>
			</div>
			<style>
			.followUl>li{margin: 15px 5px}
</style>
			";
        $button = "<input type='button' class='button' value='".L('kehuStaff.add.sub')."' onclick=\"subForm('followForm',root+'control/adIndex.html?cla=kehuStaff&fun=addEdit')\">";
        $html .= <<<eof
<script>
 function followQuick(e){
     let val = $(e).text();
     $(e).parent().find("li").css('background-color',"#ccc");
     $(e).css('background-color','#9ED0FF');
     $("[name='followType']").val(val)
 }
  function workFlowQuick(e){
     let val = $(e).text();
     $(e).parent().find("li").css('background-color',"#ccc");
     $(e).css('background-color','#9ED0FF');
     $("[name='workFlow']").val(val)
 }
</script>
eof;

        return $this->layer(array("title" => L('kehuStaff.add.edit'), "height" => 500, "width" => 800, "html" => $html, "button" => $button));
    }

    /**
     * 添加跟进
     */
    public function addEdit()
    {
        $id = $this->post('targetId');
        $backlogType = '客户跟进';
        $info = query(self::table, "id = '$id'");
        $kehu = query("kehu", " khid = '$info[khid]' ");
        $followText = $this->post('text') ."【".$this->control['name']."】";//添加后缀，防止管理员被删除后无法通过管理员id查询到管理员姓名
        //赋值
        $field = array(
            "id" => suiji(),
            'coid'=>self::$coid,
            "stid" => $this->control['stid'],
            'kehuStaffId'=>$info['id'],
            'targetName'=>$kehu['companyName'],
            'contactName'=>$info['name'],
            "target" =>'客户',//跟进对象
            "targetId" => $kehu['khid'],//跟进对象ID号
            "text" => $followText,
            "followType"=>$this->post('followType'),
            "time" => date("Y-m-d H:i:s"),//创建时间
        );
        //是否存在相同的下次跟进日期提醒计划
        $repeatNum = sqlNum("backlog"," stid = '".$this->control['stid']."' and type = '$backlogType' and typeId = '$field[targetId]' and startDay = '".$this->post('startDay')."' ");
        //当天是否提交相同内容的跟进信息
        $repeatTxt = sqlNum("follow"," stid = '".$this->control['stid']."' and target = '$field[target]' and targetId = '$field[targetId]' and text = '$followText' and time > '{$this->date}' ");
        //判断
        if (!$this->power('client', "newFollow")) {
            $json['warn'] = L('kehuStaff.addEdit.power');
        } elseif(empty($field['target'])){
            $json['warn'] = L('kehuStaff.addEdit.objEmpty');
        }elseif(empty($field['targetId'])){
            $json['warn'] = L('kehuStaff.addEdit.idEmpty');
        }elseif(empty($this->post('text'))){
            $json['warn'] = L('kehuStaff.addEdit.textEmpty');
        }elseif(empty($field['kehuStaffId'])){
            $json['warn'] = L('kehuStaff.addEdit.contactEmpty');
        }elseif(!empty($this->post('startDay')) and $this->post('startDay') < $this->date){
            $json['warn'] = L('kehuStaff.addEdit.startDayError');
        }elseif(!empty($this->post('startDay')) and $repeatNum > 0){
            $json['warn'] = L('kehuStaff.addEdit.startDayRepeat');
        }elseif($repeatTxt > 0){
            $json['warn'] = L('kehuStaff.addEdit.contentRepeat');
        } else {
            $json['warn'] = insert(array("table" => "follow", "field" => $field));
        }
        if (in_array($json['warn'], array("新增成功", "更新成功"))) {
            update(array('table'=>'kehu','field'=>['workFlow'=>$this->post('workFlow')],'where'=>"khid = '$field[targetId]'"));
            //添加日志
            $text = str_replace(['{{staffName}}','{{companyName}}','{{khid}}'], [$this->control['name'],$kehu['companyName'],$kehu['khid']], L('kehuStaff.addEdit.log')) . $this->post('text');
            $this->logText(array("type" => self::page, "text" => $text));
            //返回
            $_SESSION['warn'] = $json['warn'];
            $json['warn'] = 2;
        }
        return json_encode($json, 320);
    }

    /**
     * 编辑
     * @return bool|string
     */
    public function edit()
    {
        $kehuStaff = query("kehu_staff", " id = '" . $this->post('id') . "' ");
        if (empty($html)) {
            $html = $this->layerEdit(array("table" => array(
                array(
                    must . L('kehuStaff.homeSearch.companyName')."：" => clientClass::kehuSelect(array('name'=>'khid','value'=>$kehuStaff['khid'])),
                    must . L('kehuStaff.homeSearch.name')."：" => text(array("name" => "name", "class" => "text", "value" => $kehuStaff['name'])),
                ),
                array(
                    must . L('kehuStaff.homeSearch.sex')."：" => radio(array("name" => "sex", 'value' => ['男', '女'], "checked" => $kehuStaff['sex'])),
                    L('kehuStaff.homeSearch.department')."：" => text(array("name" => "department", "class" => "text", "value" => $kehuStaff['department'])),
                ),
                array(
                    L('kehuStaff.homeSearch.position')."：" => text(array("name" => "position", "class" => "text", "value" => $kehuStaff['position'])),
                   L('kehuStaff.homeSearch.tel')."：" => text(array("name" => "tel", "class" => "text", "value" => $kehuStaff['tel'])),
                ),
                array(
                    L('kehuStaff.homeSearch.phone')."：" => text(array("name" => "phone", "class" => "text", "value" => $kehuStaff['phone'])),
                    L('kehuStaff.homeSearch.WeChat')."：" => text(array("name" => "WeChat", "class" => "text", "value" => $kehuStaff['WeChat'])),
                ),
                array(
                    L('kehuStaff.homeSearch.qq')."：" => text(array("name" => "qq", "class" => "text textPrice", "value" => $kehuStaff['qq'])),
                    L('kehuStaff.homeSearch.address')."：" => text(array("name" => "address", "class" => "text", "value" => $kehuStaff['address'])),
                ),
                array(
                    L('kehuStaff.homeSearch.birthDay')."：" => text(array("name" => "birthDay", "class" => "text", 'laydate' => [], "value" => self::null($kehuStaff['birthDay'], false))),
                ),
                array(
                    L('kehuStaff.homeSearch.text')."：" => textarea(array("name" => "text", "class" => "textarea", "value" => $kehuStaff['text'])),
                )
            )));
        }
        return $this->layer(array("title" => L('kehuStaff.homeSearch.edit'), "height" => 450, "width" => 800, "html" => $html));
    }

    /**
     * 编辑
     * @return bool|string
     */
    public function editEdit()
    {
        $id = $this->post('id');
        //赋值
        $field = array(
            'coid'=>self::$coid,
            'khid' => $this->post('khid'),
            "sex" => $this->post('sex'),
            "position" => $this->post('position'),//职位
            "name" => $this->post('name'),//姓名
            "department" => $this->post('department'),
            "birthDay" => $this->post('birthDay'),
            "tel" => $this->post('tel'),//手机
            "phone" => $this->post('phone'),//座机
            "qq" => $this->post('qq'),//QQ号码
            "WeChat" => $this->post('WeChat'),//微信号
            "address" => $this->post('address'),//排序号
            "text" => $this->post('text'),//备注
            "updateTime" => date("Y-m-d H:i:s"),//更新时间
        );
        $kehu = query("kehu", " khid = '$field[khid]' ");
        $info = query(self::table, "id = '$id'");
        //判断
        if (!$this->power("client", "staffEdit")) {
            $json['warn'] = L('kehuStaff.editEdit.power');
        } elseif (empty($kehu['khid'])) {
            $json['warn'] = L('kehuStaff.editEdit.empty');
        } elseif (empty($field['name'])) {
            $json['warn'] = L('kehuStaff.editEdit.nameEmpty');
        } elseif (empty($field['sex'])) {
            $json['warn'] = L('kehuStaff.editEdit.sexEmpty');
        } /*elseif (empty($field['tel'])) {
            $json['warn'] = L('kehuStaff.editEdit.telEmpty');
        } elseif (preg_match(checkTel, $field['tel']) == 0) {
            $json['warn'] = L('kehuStaff.editEdit.telFormatError');
        } */elseif (!empty($field['tel']) && sqlNum("kehu_staff", " tel = '$field[tel]' and khid = '$kehu[khid]' and id != '" . $id . "' ") > 0) {
            $json['warn'] = L('kehuStaff.editEdit.contactRepeat');
        } elseif (!empty($field['qq']) and preg_match(checkInteger, $field['qq']) == 0) {
            $json['warn'] = L('kehuStaff.editEdit.qqFormatError');
        } elseif (empty($info['id'])) {
            $field = array_merge($field, array("id" => $id, "stid" => $this->control['stid'], "khid" => $kehu['khid'], "time" => date("Y-m-d H:i:s")));
            $json['warn'] = insert(array("table" => "kehu_staff", "field" => $field));
        } else {
            $json['warn'] = update(array("table" => "kehu_staff", "field" => $field, "where" => " id = '$info[id]' "));
        }
        if (in_array($json['warn'], array("新增成功", "更新成功"))) {
            //添加日志
            $type = mb_substr($json['warn'], 0, 2, 'utf-8');
            $text = str_replace(['{{staffName}}','{{companyName}}','{{khid}}','{{type}}','{{name}}'], [$this->control['name'],$kehu['companyName'],$kehu['khid'],$type,$field['name']], L('kehuStaff.editEdit.log')). $this->post('id');
            $this->logText(array("type" => "client", "text" => $text));
            //返回
            $_SESSION['warn'] = $json['warn'];
            $json['warn'] = 2;
        }
        return json_encode($json, 320);
    }


    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $word = $power = '';
        $page = self::page;
        switch ($act) {
            default:
                $page = 'client';
                $act = 'staffDel';
                $msg = L('kehuStaff.operate.del');
                $title = 'clientContactsDelete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }

        if (!$this->power($page, $act)) {
            $_SESSION['warn'] = str_replace(['{{msg}}'], [$msg], L('kehuStaff.operate.warn'));
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
                'word' => $word,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power('client', "staffDel")) {
            $json['warn'] = L('kehuStaff.delete.power');
        } elseif (empty($array)) {
            $json['warn'] = L('kehuStaff.delete.noChoice');
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                $kehu = query('kehu', " khid = '$info[khid]'");
                if ($kehu['manager'] != self::$stid) {
                    //返回
                    $warn = L('kehuStaff.delete.fail');
                } else {
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    //返回
                    $warn = L('kehuStaff.delete.success');
                    $x++;
                }
                $text .= str_replace(['{{name}}','{{id}}'], [$info['name'],$info['id']], L('kehuStaff.delete.text')) . $warn . "。<br>";
            }
            //添加日志
            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('kehuStaff.delete.log')). "<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('kehuStaff.delete.warn'));
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

    /**
     * 下载模板
     */
    public function downloadModel()
    {
        $templateId = $this->get('templateId');
        if (!$this->power(self::page, 'import')) {
            $_SESSION['warn'] = L('kehuStaff.downloadModel.power');
        } else {
            $exampleData[] = [];
            $excel    = $this->excelHead();
            $fileName = self::title.'导入模板-'.importTemplateClass::getName($templateId).'.xlsx';
            $filePath = $excel->fileName($fileName, 'sheet1');
            $format = new \Vtiful\Kernel\Format($filePath->getHandle());
            $templateField = importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
            $index         = 0;
            foreach ($templateField as $k => $array) {
                if ($array['display']){
                    $backgroundStyle=null;
                    if (importTemplateClass::getIsMustValue($this->importFieldInit(), $array['columnName'])){
                        //必填项判断
                        $backgroundStyle  = $format->background(
                            0xFFC04B
                        )->toResource();
                    }
                    $filePath->insertText(0, $index, $array['aliasName'],'',$backgroundStyle);
                    foreach ($exampleData as $y=>$example){
                        $exampleVal = match ($array['columnName']){
                            '客户名称'=>$example[0],
                            '姓名'=>$example[1],
                            '性别'=>$example[2],
                            '部门'=>$example[3],
                            '职务'=>$example[4],
                            '手机'=>$example[5],
                            '电话'=>$example[6],
                            '微信'=>$example[7],
                            'QQ'=>$example[8],
                            '生日'=>$example[9],
                            '地址'=>$example[10],
                            '备注'=>$example[11],
                            default=>'',
                        };
                        $filePath->insertText($y+1, $index, $exampleVal);
                    }
                    $index++;
                }
            }
            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('kehuStaff.downloadModel.log'));
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOutPut($filePath,$fileName);
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }


    /*数据导入*/
    public function importData()
    {
        $templateId = $this->post('templateId');
        if (!$this->power(self::page, 'import')) {
            $json['warn'] = L('kehuStaff.importData.power');
        } else {
             $fomatArray = [];//导入数据格式同一为TYPE_STRING
            foreach ($this->importFieldInit() as $value){
                $fomatArray[] = \Vtiful\Kernel\Excel::TYPE_STRING;
            }
            $data = $this->importHead(format: $fomatArray);
            $x = 0;
            $text = '';
            $headArray = [];
            $row_list=0;
            foreach ($data as $i => $row) {
                $row_list++;
                if ($i==0){
                    $templateField = importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
                    $headArray = importTemplateClass::combinHead($templateField,$row);
                }
                if ($i > 0) {
                    $rowData = formSubArray($row);
                    //只接收模板中选中的字段的值
                    $cell = [];
                    foreach ($headArray as $index=>$headName){
                        $cell[$headName] = $rowData[$index]??'';
                    }
                    //初始化未被模板需要的字段的值
                    foreach ($this->importFieldInit() as $value){
                        $cell[$value['columnName']] = $cell[$value['columnName']]??'';
                    }
                    $kehu = query('kehu', "companyName = '$cell[客户名称]'");

                    $id = self::getId();
                    $field = [
                        'id' => $id,
                        'coid'=>self::$coid,
                        'khid' => $kehu['khid'],
                        "sex" => $cell['性别'],
                        "position" => $cell['职务'],
                        "name" => $cell['姓名'],//姓名
                        "department" => $cell['部门'],
                        "birthDay" => $cell['生日'],
                        "tel" => $cell['手机'],
                        "phone" => $cell['电话'],
                        "qq" => $cell['QQ'],
                        "WeChat" => $cell['微信'],
                        "address" => $cell['地址'],
                        "text" => $cell['备注'],
                        "updateTime" => date("Y-m-d H:i:s"),//更新时间
                        'time' => $this->time,
                    ];
                    if (empty($kehu['khid'])) {
                        $text .= str_replace(['{{i}}'], [$row_list], L('kehuStaff.importData.clientEmpty'));
                    } elseif (empty($field['name'])) {
                        $text .= str_replace(['{{i}}'], [$row_list], L('kehuStaff.importData.nameEmpty'));
                    } elseif (empty($field['sex'])) {
                        $text .= str_replace(['{{i}}'], [$row_list], L('kehuStaff.importData.sexEmpty'));
                    } elseif (empty($field['tel'])) {
                        $text .= str_replace(['{{i}}'], [$row_list], L('kehuStaff.importData.telEmpty'));
                    } elseif (preg_match(checkTel, $field['tel']) == 0) {
                        $text .= str_replace(['{{i}}'], [$row_list], L('kehuStaff.importData.telFormatError'));
                    } elseif (sqlNum("kehu_staff", " tel = '$field[tel]' and khid = '$kehu[khid]'") > 0) {
                        $text .= str_replace(['{{i}}'], [$row_list], L('kehuStaff.importData.contactRepeat'));
                    } elseif (!empty($field['qq']) and preg_match(checkInteger, $field['qq']) == 0) {
                        $text .= str_replace(['{{i}}'], [$row_list], L('kehuStaff.importData.qqFormatError'));
                    } else {
                        //查看范围
                        $warn = insert(["table" => self::table, "field" => $field]);
                        if (in_array($warn, ["新增成功", "更新成功"])) {
                            $x++;
                            $text .= str_replace(['{{i}}'], [$row_list], L('kehuStaff.importData.success'))."<br>";
                        } else {
                            $text .= str_replace(['{{i}}'], [$row_list], L('kehuStaff.importData.fail'))."<br>";
                        }
                    }
                }
            }
            $total = count($data)-1;
            $json['data'] = [
                'text'=>$text,
                'title'=>"您导入了{$total}条数据，成功{$x}条，失败".($total-$x)."条",
            ];
            $text = str_replace(['{{staffName}}','{{fileName}}'], [$this->control['name'],$_FILES['file']['name']], L('kehuStaff.importData.log')) . $text;
            $this->logText(["type" => self::page, "text" => $text]);
            $json['warn'] = 2;
        }
        return json_encode($json,320);
    }


    /**
     * 导出
     */
    public function exportData()
    {
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = L('kehuStaff.exportData.power');
        }  else {
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            //判断是否选中导出
            if (!self::is_null_array($checkedId)){
                $result = find(array(
                    'field' => "a.*,b.companyName",
                    "table" => "kehu_staff as a join kehu as b on a.khid = b.khid",
                    "where" => "a.id in ('".implode("','", $checkedId)."') order by a.updateTime desc",
                ))['array'];
            }else{
                $sql   = $_SESSION[self::page]['sql'];
                $result   = sqlFind($sql);
            }
            //导出数据生成
            foreach ($result as $array){
                $column = [];
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '客户名称'=>$array['companyName'],
                            '姓名'=>$array['name'],
                            '性别'=>$array['sex'],
                            '部门'=>$array['department'],
                            '职务'=>$array['position'],
                            '手机'=>$array['tel'],
                            '电话'=>$array['phone'],
                            '微信'=>$array['WeChat'],
                            'QQ'=>$array['qq'],
                            '生日'=>self::null($array['birthDay']),
                            '地址'=>$array['address'],
                            '备注'=>$array['text'],
                            '更新时间'=>$array['updateTime'],
                            '创建时间'=>$array['time'],
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }
            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('kehuStaff.exportData.log'));
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, L('kehuStaff.exportData.fileName').".xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }

    /**
     * 导入模板字段初始化
     * @return array[]
     */
    public function importFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'客户名称',
                    'aliasName'=>'客户名称',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'姓名',
                    'aliasName'=>'姓名',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'性别',
                    'aliasName'=>'性别',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'部门',
                    'aliasName'=>'部门',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'职务',
                    'aliasName'=>'职务',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'手机',
                    'aliasName'=>'手机',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'电话',
                    'aliasName'=>'电话',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'微信',
                    'aliasName'=>'微信',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'QQ',
                    'aliasName'=>'QQ',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'生日',
                    'aliasName'=>'生日',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'地址',
                    'aliasName'=>'地址',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'备注',
                    'aliasName'=>'备注',
                    'isMust'=>false,
                ],
            ]
        };
    }

    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'客户名称',
                    'aliasName'=>'客户名称',
                ],
                [
                    'columnName'=>'姓名',
                    'aliasName'=>'姓名',
                ],
                [
                    'columnName'=>'性别',
                    'aliasName'=>'性别',
                ],
                [
                    'columnName'=>'部门',
                    'aliasName'=>'部门',
                ],
                [
                    'columnName'=>'职务',
                    'aliasName'=>'职务',
                ],
                [
                    'columnName'=>'手机',
                    'aliasName'=>'手机',
                ],
                [
                    'columnName'=>'电话',
                    'aliasName'=>'电话',
                ],
                [
                    'columnName'=>'微信',
                    'aliasName'=>'微信',
                ],
                [
                    'columnName'=>'QQ',
                    'aliasName'=>'QQ',
                ],
                [
                    'columnName'=>'生日',
                    'aliasName'=>'生日',
                ],
                [
                    'columnName'=>'地址',
                    'aliasName'=>'地址',
                ],
                [
                    'columnName'=>'备注',
                    'aliasName'=>'备注',
                ],
                [
                    'columnName'=>'更新时间',
                    'aliasName'=>'更新时间',
                ],
                [
                    'columnName'=>'创建时间',
                    'aliasName'=>'创建时间',
                ],
            ]
        };
    }

}
